package com.icinema.server.builders;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.icinema.server.factories.EntityFactory;
import com.icinema.vo.Cinema;
import com.icinema.vo.Movie;
import com.icinema.vo.MovieShowing;
import com.icinema.vo.MovieShowingDetail;

public class MovieDetailListBuilder {
	
	DatastoreService datastore;
	
	public void setDatastore(DatastoreService datastore) {
		this.datastore = datastore;
	}

	public List<MovieShowingDetail> getMovieShowings() {
		Query query = new Query(MovieShowing.class.getSimpleName());
		
		List<MovieShowing> results = new ArrayList<MovieShowing>();
		
		for(Entity entity : datastore.prepare(query).asIterable(FetchOptions.Builder.withDefaults())) {
			results.add(new EntityFactory<MovieShowing>().toMovieShow(entity));
		}
		List<MovieShowingDetail> detailList = new ArrayList<MovieShowingDetail>();
		for(MovieShowing movieShowing:results){
			MovieShowingDetail detail = new MovieShowingDetail();
			detail.setMovieShowing(movieShowing);
			Entity movieEntity;
			try {
				movieEntity = datastore.get(KeyFactory.stringToKey(movieShowing.getMovieId()));
				Entity cinemaEntity = datastore.get(KeyFactory.stringToKey(movieShowing.getCinemaId()));
				detail.setMovie(new EntityFactory<Movie>().toMovie(movieEntity));
				detail.setCinema(new EntityFactory<Cinema>().toCinema(cinemaEntity));
				detailList.add(detail);
			} catch (EntityNotFoundException e) {
				e.printStackTrace();
			}			
		}
		
		return detailList;
	}
}
